"""
评价系统路由
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from database import get_db
from auth import get_current_active_user
from models import Review, Trade, User
from schemas import ReviewResponse, ReviewCreate, BaseResponse, PaginatedResponse

router = APIRouter()

@router.post("/", response_model=ReviewResponse)
async def create_review(
    review_data: ReviewCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建评价"""
    # 检查交易是否存在且已完成
    trade = db.query(Trade).filter(
        Trade.id == review_data.trade_id,
        Trade.status == 'completed'
    ).first()
    
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在或未完成"
        )
    
    # 检查用户是否参与此交易
    if trade.buyer_id != current_user.id and trade.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权评价此交易"
        )
    
    # 确定评价对象
    if trade.buyer_id == current_user.id:
        # 买家评价卖家
        reviewed_user_id = trade.seller_id
        review_type = 'seller'
    else:
        # 卖家评价买家
        reviewed_user_id = trade.buyer_id
        review_type = 'buyer'
    
    # 检查是否已评价
    existing_review = db.query(Review).filter(
        Review.trade_id == review_data.trade_id,
        Review.reviewer_id == current_user.id
    ).first()
    
    if existing_review:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已评价过此交易"
        )
    
    # 创建评价
    review = Review(
        trade_id=review_data.trade_id,
        reviewer_id=current_user.id,
        reviewed_user_id=reviewed_user_id,
        rating=review_data.rating,
        comment=review_data.comment,
        review_type=review_type
    )
    
    db.add(review)
    db.commit()
    db.refresh(review)
    
    return review

@router.get("/user/{user_id}", response_model=PaginatedResponse)
async def get_user_reviews(
    user_id: int,
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    review_type: Optional[str] = Query(None, description="评价类型：buyer/seller"),
    db: Session = Depends(get_db)
):
    """获取用户评价列表"""
    # 检查用户是否存在
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    query = db.query(Review).filter(Review.reviewed_user_id == user_id)
    
    # 评价类型筛选
    if review_type:
        query = query.filter(Review.review_type == review_type)
    
    # 按创建时间倒序排列
    query = query.order_by(Review.created_at.desc())
    
    # 分页
    total = query.count()
    reviews = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=reviews,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.get("/trade/{trade_id}", response_model=List[ReviewResponse])
async def get_trade_reviews(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取交易评价"""
    # 检查交易是否存在
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.buyer_id != current_user.id and trade.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权查看此交易评价"
        )
    
    reviews = db.query(Review).filter(Review.trade_id == trade_id).all()
    return reviews

@router.get("/my-reviews/", response_model=PaginatedResponse)
@router.get("/my", response_model=PaginatedResponse)
async def get_my_reviews(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    role: Optional[str] = Query(None, description="角色：reviewer（我评价的）/reviewed（评价我的）"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取我的评价"""
    if role == 'reviewer':
        # 我评价别人的
        query = db.query(Review).filter(Review.reviewer_id == current_user.id)
    elif role == 'reviewed':
        # 别人评价我的
        query = db.query(Review).filter(Review.reviewed_user_id == current_user.id)
    else:
        # 默认获取所有与我相关的评价
        query = db.query(Review).filter(
            (Review.reviewer_id == current_user.id) | 
            (Review.reviewed_user_id == current_user.id)
        )
    
    # 按创建时间倒序排列
    query = query.order_by(Review.created_at.desc())
    
    # 分页
    total = query.count()
    reviews = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=reviews,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.get("/user/{user_id}/stats", response_model=dict)
async def get_user_review_stats(
    user_id: int,
    db: Session = Depends(get_db)
):
    """获取用户评价统计"""
    # 检查用户是否存在
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 作为卖家的评价统计
    seller_reviews = db.query(Review).filter(
        Review.reviewed_user_id == user_id,
        Review.review_type == 'seller'
    )
    
    seller_total = seller_reviews.count()
    seller_avg_rating = seller_reviews.with_entities(
        db.func.avg(Review.rating).label('avg_rating')
    ).scalar() or 0
    
    # 作为买家的评价统计
    buyer_reviews = db.query(Review).filter(
        Review.reviewed_user_id == user_id,
        Review.review_type == 'buyer'
    )
    
    buyer_total = buyer_reviews.count()
    buyer_avg_rating = buyer_reviews.with_entities(
        db.func.avg(Review.rating).label('avg_rating')
    ).scalar() or 0
    
    # 评分分布
    rating_distribution = db.query(
        Review.rating,
        db.func.count(Review.id).label('count')
    ).filter(
        Review.reviewed_user_id == user_id
    ).group_by(Review.rating).all()
    
    rating_dist = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
    for rating, count in rating_distribution:
        rating_dist[rating] = count
    
    return {
        'seller_stats': {
            'total_reviews': seller_total,
            'avg_rating': round(seller_avg_rating, 1),
            'rating_distribution': rating_dist
        },
        'buyer_stats': {
            'total_reviews': buyer_total,
            'avg_rating': round(buyer_avg_rating, 1),
            'rating_distribution': rating_dist
        },
        'overall_stats': {
            'total_reviews': seller_total + buyer_total,
            'avg_rating': round((seller_avg_rating * seller_total + buyer_avg_rating * buyer_total) / (seller_total + buyer_total) if (seller_total + buyer_total) > 0 else 0, 1)
        }
    }

@router.put("/{review_id}", response_model=ReviewResponse)
async def update_review(
    review_id: int,
    review_data: ReviewCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新评价"""
    review = db.query(Review).filter(Review.id == review_id).first()
    if not review:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="评价不存在"
        )
    
    # 检查权限
    if review.reviewer_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权修改此评价"
        )
    
    # 更新评价信息
    review.rating = review_data.rating
    review.comment = review_data.comment
    
    db.commit()
    db.refresh(review)
    
    return review

@router.delete("/{review_id}", response_model=BaseResponse)
async def delete_review(
    review_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除评价"""
    review = db.query(Review).filter(Review.id == review_id).first()
    if not review:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="评价不存在"
        )
    
    # 检查权限
    if review.reviewer_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权删除此评价"
        )
    
    db.delete(review)
    db.commit()
    
    return BaseResponse(message="评价删除成功")